#coding=utf-8
import inspect
import math
import time
from time import strftime,gmtime,localtime
import datetime
import hashlib
import base64


def is_array(param):
    return isinstance(param,(list,tuple,dict))

def in_array(needle,haystack):
    if needle in haystack:
        return True
    return False


def in_array_r(needle,haystack):
    for item in haystack:
        if item == needle or is_array(item) and in_array_r(needle,item):
            return True
    return False

#function in_array_r($needle, $haystack) {
#    foreach ($haystack as $item) {
#        if ($item === $needle || (is_array($item) && in_array_r($needle, $item))) {
#            return true;
#        }
#    }
#
#    return false;
#}


def strstr(needle,haystack,offset=None):
    haystack = str(haystack)
    pos = haystack.find(needle,offset)
    if pos < 0:
        return False
    else:
        return haystack[pos:]

def memory_usage():
    """Memory usage of the current process in kilobytes."""
    status = None
    result = {'peak': 0, 'rss': 0}
    try:
        # This will only work on systems with a /proc file system
        # (like Linux).
        status = open('/proc/self/status')
        for line in status:
            parts = line.split()
            key = parts[0][2:-1].lower()
            if key in result:
                result[key] = int(parts[1])
    finally:
        if status is not None:
            status.close()
    return result

def numberFormat(number,point=2):
    number = float(number)
    res = ("%." + str(point) +"f") % number
    return res

def addslashes(s):
    if not s:
        return ''
    d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}
    return ''.join(d.get(c, c) for c in s)

def array_flip(arr):
    result = dict((v,k) for k,v in arr.items())
    #result = dict(zip(trans.values(), trans.keys()))
    return result

def substr(str):
    res = str.split(".")
    return res[len(res) - 1]

def implode(glue="",barray=[]):
	if type(glue)==list:
		barray=glue;
		glue=""
	temp_list=map(unicode,barray);
	return glue.join(temp_list);

def explode(delimiter,stack):
    return stack.split(delimiter)


def serialize(input_str):
    from phpserialize import dumps
    return dumps(input_str)

def unserialize(input_str):
    from phpserialize import loads
    return loads(input_str)

def extract(vars):
    caller = inspect.stack()[1][0] # caller of extract()
    for n, v in vars.items():
        caller.f_locals[n] = v


def addLog(filePath,contents):
    handle = open(filePath,'w')
    handle.write("\r\n" + str(contents) + "\r\n")
    handle.close()

def ceil(value):
    return int(math.ceil(value))

def setTime(timestamp):
    return strftime("%Y%m%d", localtime(timestamp))

def getTime(timestamp):
    return setTime(timestamp)

def getIntDate(timestamp=None):
    if None == timestamp:
        tmpTime = int(time.time())
    else:
        tmpTime = timestamp
    return getDate(setTime(tmpTime))

def getIntTimestamp(date):
    tmp = getDate(date)
    return getTime(tmp)

def getDate(date,type=''):
    if '-' == type :
        year = int(date[:4])
        month = int(date[5:-3])
        day = int(date[8:])
    else:
        year = int(date[:4])
        month = int(date[4:-2])
        day = int(date[6:])
    st = datetime.datetime(year,month,day,0,0,0)
    return int(time.mktime(st.timetuple()))


def extDump(obj,isExit=True):
    print obj
    if isExit:
        exit()

def ed(obj,isExit=True):
    print obj
    if isExit:
        exit()

def array_merge(arr1=[],arr2=[]):
    return arr1.extend(arr2)
    

def passportDecrypt(txt, key = 'fsdjk2rt'):
    s = base64.decodestring(txt)
    txt = passportKey(s, key)
    tmp = ''
    for i in range(len(txt)):
        md5 = txt[i]
        k = i + 1
        if k == len(txt):
            k = 0
        tmp += unichr(ord(txt[k]) ^ ord(md5))
    
    rs = ''
    for s in range(len(tmp)):
        if s % 2 == 1:
            continue
        rs += tmp[s]
    return rs

def passportKey(txt, key):
    md5 = hashlib.md5(key).hexdigest()
    encrypt_key = md5
    ctr = 0
    tmp = ''

    for i in range(len(txt)):
        ctr = 0 if ctr == len(encrypt_key) else ctr
        tmp += unichr(ord(txt[i]) ^ ord(encrypt_key[ctr]))
        ctr += 1
    return tmp


def get_url_contents(filename):
    import urllib2
    return urllib2.urlopen(filename).read()

def file_get_contents(filename):
    import urllib2
    try:
        return urllib2.urlopen(filename).read()
    except:
        return open(filename).read()

def file_get_contents2(filename):
    import urllib2
    ret = ''
    try:
        ret = urllib2.urlopen(filename).read()
    except:
        for i in range(10):
            try:
                ret = urllib2.urlopen(filename).read()       
            except:
                pass
            if ret:
                break
    if ret:
        return ret
    else:
        return False
        

def file_put_contents(path,contents):
    f = open(path, 'w+')
    f.write(str(contents))
    f.close()

#获取当前路径
def getpwd():
    import sys,os
    pwd = sys.path[0]
    if os.path.isfile(pwd):
        pwd = os.path.dirname(pwd)
        return pwd

def repurl(url):
    newUrl = str(url)
    newUrl = newUrl.replace('??','?').replace('&&','&').replace('.?','?').replace('&=','')
    return newUrl

def parse_url(url):
    import urlparse
    res = urlparse.urlparse(url)
    
    dt = {
        'scheme':res.scheme,
        'host':res.hostname,
        'user':res.username,
        'pass':res.password,
        'path':res.path,
        'query':res.query,
        'fragment':res.fragment,
    }
    return dt

def parse_str(str):
    import urlparse
    return urlparse.parse_qsl(str) # {'first': 'value', 'sec': 'foo bar'}

def my_urlencode(s) :
    reprStr = repr(s).replace(r'\x', '%')
    return reprStr[1:-1]

def to_list(t):
    return [i if not isinstance(i, tuple) else to_list(i) for i in t]

def trim(s):
    return s.lstrip().rstrip()

def decodeGUrl(urlKeyString):
    import hashlib
    import base64
    newurl = base64.decodestring(urlKeyString)
    return newurl

def findErrorGUrl(urlKeyString):
    import urlparse, urllib
    flag = True
    key = decodeGUrl(urlKeyString)
    #res = explode('&',key)
    res = urlparse.parse_qs(key,1)
    if res['utm_groupid'] == ['']:
        flag = False
    return flag

def getSurveyUrl(url, searchen=1):
    import seturl
    return seturl.getSurveyUrl(url, searchen)

def checkWhetherSetUrl(url):
    import seturl
    return seturl.checkWhetherSetUrl(url)

def reurl(url):
    import seturl
    return seturl.reurl(url)


def fib(x):
    time.sleep(0.001)
    if x < 2: return 1
    return (fib(x - 2) + fib(x - 1))

def fac(x):
    time.sleep(0.1)
    if x < 2: return 1
    return (x * fac(x-1))

def sum(x):
    time.sleep(0.1)
    if x < 2: return 1
    return (x + sum(x - 1))

if __name__ == '__main__':
    #print passportDecrypt('B0RbKgI+An0EOAVt')
    res = unserialize('a:2:{i:0;i:1;i:1;i:23;}')
    a = [1,2,3]
    print implode(',', a)
    print res
